package com.leetcode;

import ds.ListNode;

import java.util.Scanner;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No19
 * @description 19. 删除链表的倒数第 N 个结点
 * @date 2021/3/14 下午6:03
 */
public class No19 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode t1 = new ListNode(2);
        ListNode t2 = new ListNode(3);
        ListNode t3 = new ListNode(4);
        ListNode t4 = new ListNode(5);
        ListNode t5 = new ListNode(6);
        head.next = t1;
        t1.next = t2;
        t2.next = t3;
        t3.next = t4;
        t4.next = t5;
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ListNode res = removeNthFromEnd(head,n);
        print(res);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || head.next == null|| n <= 0){
            return null;
        }
        ListNode fast = head;
        while (n-- > 0){
            fast = fast.next;
        }
        if(fast == null){
            return head.next;
        }
        ListNode slow = head;
        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }

    public static void print(ListNode head){
        while (head != null){
            System.out.print(head.val);
            System.out.print(" ");
            head = head.next;
        }
    }

}
